<template>
  <div>
    <van-nav-bar title="注册" left-text="返回" left-arrow />

    <van-form @submit="onSubmit" ref="myform">
      <!-- van-field 字段的name就是发送给后端接口的字段 -->
      <van-field
        v-model="mytel"
        name="regphone"
        label="手机号"
        placeholder="手机号"
        :rules="[{ required: true, message: '请填写手机号' }, { pattern: /^1[3-9]\d{9}$/, message: '请填写正确的手机号' },]"
      />
      <van-field
        v-model="password"
        type="password"
        name="regpwd"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />

      <van-field v-model="sms" center clearable label="短信验证码" name="code" placeholder="请输入短信验证码">
        <template #button>
          <van-count-down
            :time="1000 * 60"
            format="ss s"
            v-if="showCount"
            @finish="showCount=false"
          />
          <van-button size="small" type="primary" @click.prevent="sendSms" v-else>发送验证码</van-button>
        </template>
      </van-field>

      <div style="margin: 16px;">
        <van-button block type="info" native-type="submit">注册</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { Toast } from "vant";
import request from "@/api/user.js";
export default {
  data() {
    return {
      mytel: "",
      password: "",
      sms: "",
      showCount: false,
    };
  },
  methods: {
    onSubmit(values) {
      console.log(values);
      //  注册
      request.register(values).then((r) => {
        console.log(r.data);
        if (r.data.code === 0) {
          Toast.success("注册成功！");
          this.mytel = ""
          this.password = ""
          this.sms = ""
          this.$router.push('/login')
        } else {
          Toast.fail(r.data.msg);
        }
      });
    },

// 发送验证码、
// validate()方法里面写要验证的字段， 如果不写，就是验证整个表单
    sendSms() {
      this.$refs["myform"]
        .validate("regphone")
        .then((r) => {
          // 手机号验证通过后，调用发送验证码的接口
          this.showCount = true;
          request.sendSms({ phone: this.mytel }).then((r) => {
            console.log(r.data);
            if (r.data.code === 0) {
              Toast.success("验证码发送成功");
            } else {
              Toast.fail(r.data.msg);
            }
          });
        })
        .catch((r) => {
          // console.log('请填写正确的手机号');
          Toast.fail({
            message: "请填写正确的手机号",
            position: "top",
          });
        });
    },
  },
};
</script>

<style >
.van-nav-bar {
  background-color: rgb(5, 128, 235);
}
.van-nav-bar__title {
  color: #fff !important;
}
.van-nav-bar .van-icon {
  color: #fff;
}
.van-nav-bar__text {
  color: #fff;
}
</style>